package lanou3g.myfirstapp36kr.fragment;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;
import lanou3g.myfirstapp36kr.StringUrl;
import lanou3g.myfirstapp36kr.activity.NewsDetailsActivity;
import lanou3g.myfirstapp36kr.R;
import lanou3g.myfirstapp36kr.activity.SearchActivity;
import lanou3g.myfirstapp36kr.activity.TurnPicDetailsActivity;
import lanou3g.myfirstapp36kr.adapter.FragmentNewsLVAdapter;
import lanou3g.myfirstapp36kr.adapter.Item_fragment_news_lv_viewpagerAdapter;
import lanou3g.myfirstapp36kr.base.BaseFragment;
import lanou3g.myfirstapp36kr.entity.FragmentNEwsLVTVEntity;
import lanou3g.myfirstapp36kr.entity.FragmentNewsLVEntity;
import lanou3g.myfirstapp36kr.entity.FragmentNewsLVEntity.DataBean.DataBean1;
import lanou3g.myfirstapp36kr.entity.FragmentNewsTurnPic;
import lanou3g.myfirstapp36kr.myvolleysingleton.VolleySingleton;
import lanou3g.myfirstapp36kr.srcollView.RefreshLayout;
import lanou3g.myfirstapp36kr.srcollView.RefreshLayout.OnLoadListener;

/**
 * Created by dllo on 16/8/2.
 */
public class Fragmentnews extends BaseFragment implements OnClickListener {
    private DrawerLayout drawerLayout;
    private ListView listView;
    private TextView textViewNews;
    private List<FragmentNewsLVEntity> fragmentNewsLVEntities;
    private Banner banner;
    private Item_fragment_news_lv_viewpagerAdapter viewpagerAdapter;
    private View headView;
    public static List<String> strUrl = new ArrayList<>();
    private RefreshLayout swipeRefreshLayout;
    private FragmentNewsLVAdapter adapter;
    //视频
    public VideoView videoView;
    public TVAdapter tvAdapter;
    public android.widget.MediaController mediaController;
    public int currentIndex = -1;
    public int playPosition = -1;
    public boolean isPaused = false;
    public boolean isPlaying = false;
    FragmentNEwsLVTVEntity response;
    FragmentNewsTurnPic responseTurnPic;
    private int i = 0;


    //

    @Override
    protected int getLayout() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView(View view) {

        headView = LayoutInflater.from(getContext()).inflate(R.layout.headview_fragment_news_lv, null);
        banner = (Banner) headView.findViewById(R.id.head_f_news_lv_view_pager);
        View view1 = LayoutInflater.from(context).inflate(R.layout.item_fragment_news_lv_krtv, null);
        videoView = (VideoView) view1.findViewById(R.id.videoview);
        tvAdapter = new TVAdapter();
        getActivity().findViewById(R.id.search).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Fragmentnews.this.getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });


        textViewNews = (TextView) view.findViewById(R.id.news);
        drawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout);

        listView = (ListView) view.findViewById(R.id.list_view_news);
        adapter = new FragmentNewsLVAdapter(getActivity());
        listView.setAdapter(adapter);
        swipeRefreshLayout = (RefreshLayout) view.findViewById(R.id.swipe_layout);

        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                VolleySingleton.addRequest(StringUrl.stringFragmentNewsLV, FragmentNewsLVEntity.class,
                        new Response.Listener<FragmentNewsLVEntity>() {
                            @Override
                            public void onResponse(FragmentNewsLVEntity response) {
                                adapter.setEntity(response);
                                adapter.notifyDataSetChanged();
                                //ListView加点击事件跳转详情
                            }
                        }, new ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                error.getMessage();

                            }
                        });
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        swipeRefreshLayout.setmOnLoadListener(new OnLoadListener() {
            @Override
            public void onLoad() {
                Toast.makeText(context, "加载", Toast.LENGTH_SHORT).show();
                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        i++;
                        VolleySingleton.addRequest(StringUrl.STRINGS[i], FragmentNewsLVEntity.class,
                                new Response.Listener<FragmentNewsLVEntity>() {
                                    @Override
                                    public void onResponse(FragmentNewsLVEntity response) {
                                        adapter.setEntity(response);
                                        adapter.notifyDataSetChanged();
                                        swipeRefreshLayout.setLoading(false);
                                    }
                                }, new ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        error.getMessage();

                                    }
                                });

                        Log.d("+++++","" + i);

                    }
                }, 1500);
            }
        });


    }


    @Override
    protected void initData() {
        //打开抽屉
        getActivity().findViewById(R.id.btn_draw).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
        //关闭抽屉
        getActivity().findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.closeDrawers();
            }
        });
        getActivity().findViewById(R.id.iv_all).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_early).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_bturn).setOnClickListener(this);
        getActivity().findViewById(R.id.bigcompany).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_money).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_height).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_learn).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_tv).setOnClickListener(this);

        fragmentNewsLVEntities = new ArrayList<>();
        viewpagerAdapter = new Item_fragment_news_lv_viewpagerAdapter(getActivity());
        //创建请求队列

        //网络请求

        VolleySingleton.addRequest(StringUrl.stringFragmentNewsLV, FragmentNewsLVEntity.class,
                new Response.Listener<FragmentNewsLVEntity>() {
                    @Override
                    public void onResponse(FragmentNewsLVEntity response) {

                        banner.setDelayTime(3000);
                        banner.setImages(strUrl);

                        banner.setOnBannerClickListener(new OnBannerClickListener() {
                            @Override
                            public void OnBannerClick(int position) {
                                Intent intent = new Intent(Fragmentnews.this.getActivity(), TurnPicDetailsActivity.class);
                                String urlNum = responseTurnPic.getData().getPics().get(position - 1).getLocation();
                                intent.putExtra("urlNum", urlNum);
                                startActivity(intent);
                            }
                        });




//                FragmentNewsLVAdapter adapter = new FragmentNewsLVAdapter(getActivity());
                        adapter.setEntity(response);
                        listView.addHeaderView(headView);

//                listView.setAdapter(adapter);
                        //ListView加点击事件跳转详情
                        listView.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(Fragmentnews.this.getActivity(), NewsDetailsActivity.class);
                                DataBean1 bean = (DataBean1) adapterView.getAdapter().getItem(i);
                                String pictureUrl = bean.getFeatureImg();
                                //if (BuildConfig.DEBUG) Log.d("Fragmentnews______", pictureUrl);
                                intent.putExtra("pictureUrl", pictureUrl);
                                String name = bean.getUser().getName();
                                intent.putExtra("name", name);
                                //if (BuildConfig.DEBUG) Log.d("Fragmentnews===", name);
                                String title = bean.getTitle();
                                intent.putExtra("title", title);
                                String feedId = bean.getFeedId();
                                String detailsUrl = "https://rong.36kr.com/api/mobi/news/" + feedId;
                                intent.putExtra("feedId", feedId);
                                intent.putExtra("detailsUrl", detailsUrl);
                                long publishTime = bean.getPublishTime();
                                intent.putExtra("publishTime", publishTime);
                                long Id = bean.getUser().getSsoId();
                                intent.putExtra("Id", Id);
                                String columnName = bean.getColumnName();
                                intent.putExtra("columnName", columnName);
                                startActivity(intent);

                            }
                        });


                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.getMessage();

                    }
                });

        VolleySingleton.addRequest(StringUrl.stringFragmentNewsTurnPic, FragmentNewsTurnPic.class, new Response.Listener<FragmentNewsTurnPic>() {
            @Override
            public void onResponse(FragmentNewsTurnPic response) {
                for (int i = 0; i < response.getData().getPics().size(); i++) {
                    strUrl.add(response.getData().getPics().get(i).getImgUrl());
                    Fragmentnews.this.responseTurnPic = response;
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.getMessage();
            }
        });

        //将请求添加到队列中


    }

    public void request(String url) {
        VolleySingleton.addRequest(url, FragmentNewsLVEntity.class, new Response.Listener<FragmentNewsLVEntity>() {
            @Override
            public void onResponse(FragmentNewsLVEntity response) {
                Log.d("Fragmentnews", "entity:" + response.getData().getData().size());
                adapter.setEntity(response);
                listView.setAdapter(adapter);

            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.getMessage();
            }
        });

    }

    @Override
    public void onClick(View view) {
        drawerLayout.closeDrawers();
        listView.removeHeaderView(headView);
        switch (view.getId()) {
            case R.id.iv_all:

                textViewNews.setText("全部");
                listView.addHeaderView(headView);
                request(StringUrl.stringFragmentNewsAll);

                break;
            case R.id.iv_early:

                textViewNews.setText("早期项目");
                request(StringUrl.stringFragmentNEwsEarly);
                break;
            case R.id.iv_bturn:

                textViewNews.setText("B轮后");
                request(StringUrl.stringFragmentNewsBTurn);
                break;
            case R.id.bigcompany:

                textViewNews.setText("大公司");
                request(StringUrl.stringFragmentNewsBigCompany);
                break;
            case R.id.iv_money:

                textViewNews.setText("资本");
                request(StringUrl.stringFragmentNewsMoney);
                break;
            case R.id.iv_height:

                textViewNews.setText("深度");
                request(StringUrl.stringFragmentNewsHeight);
                break;
            case R.id.iv_learn:

                textViewNews.setText("研究");
                request(StringUrl.stringFragmentNewsLearn);
                break;
            case R.id.iv_tv:
                textViewNews.setText("氪TV");
                VolleySingleton.addRequest(StringUrl.stringFragmentNewsTv,
                        FragmentNEwsLVTVEntity.class, new Response.Listener<FragmentNEwsLVTVEntity>() {
                            @Override
                            public void onResponse(FragmentNEwsLVTVEntity response) {
                                Fragmentnews.this.response = response;
                                tvAdapter.setEntity(response);
                                listView.setAdapter(tvAdapter);
                                listView.setOnScrollListener(new OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(AbsListView absListView, int i) {

                                    }

                                    @Override
                                    public void onScroll(AbsListView absListView,
                                                         int firstVisibleItem,
                                                         int visibleItemCount, int totalItemCount) {
                                        if ((currentIndex < firstVisibleItem || currentIndex >
                                                listView.getLastVisiblePosition()) && isPlaying) {
                                            playPosition = videoView.getCurrentPosition();
                                            videoView.setMediaController(null);
                                            isPaused = true;
                                            isPlaying = false;
                                        }

                                    }
                                });


                            }
                        }, new ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });


        }


    }

    class TVAdapter extends BaseAdapter {
        public FragmentNEwsLVTVEntity entity;

        public void setEntity(FragmentNEwsLVTVEntity entity) {
            this.entity = entity;
        }

        @Override
        public int getCount() {
            return entity.getData().getData().size();
        }

        @Override
        public Object getItem(int i) {
            return entity.getData().getData().get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            final ViewHolder holder;
            final int position = i;
            if (view == null) {
                view = LayoutInflater.from(getActivity()).inflate(R.layout.item_fragment_news_lv_krtv, null);
                holder = new ViewHolder();
                holder.videoImage = (ImageView) view.findViewById(R.id.video_image);
                holder.videoNameText = (TextView) view.findViewById(R.id.video_name_text);
                holder.videoPlayBtn = (ImageButton) view.findViewById(R.id.video_play_btn);
                holder.progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
                view.setTag(holder);

            } else {
                holder = (ViewHolder) view.getTag();
            }
            Picasso.with(getActivity()).load(entity.getData().getData().get(i).getTv().getFeatureImg()).into(holder.videoImage);
            holder.videoNameText.setText(entity.getData().getData().get(i).getTv().getTitle());
            holder.videoPlayBtn.setVisibility(View.VISIBLE);
            holder.videoImage.setVisibility(View.VISIBLE);
            holder.videoNameText.setVisibility(View.VISIBLE);
            mediaController = new MediaController(getActivity(), false);
            if (currentIndex == position) {
                holder.videoPlayBtn.setVisibility(View.INVISIBLE);
                holder.videoImage.setVisibility(View.INVISIBLE);
                holder.videoNameText.setVisibility(View.INVISIBLE);
                if (isPlaying || playPosition == -1) {
                    if (videoView != null) {
                        videoView.setVisibility(View.GONE);
                        videoView.stopPlayback();
                        holder.progressBar.setVisibility(View.GONE);
                    }


                }
                videoView = (VideoView) view.findViewById(R.id.videoview);
                videoView.setVisibility(View.VISIBLE);
                mediaController.setAnchorView(videoView);
                mediaController.setMediaPlayer(videoView);
                videoView.setMediaController(mediaController);
                videoView.requestFocus();
                holder.progressBar.setVisibility(View.VISIBLE);
                if (playPosition > 0 && isPaused) {
                    videoView.start();
                    isPaused = false;
                    isPlaying = true;
                    holder.progressBar.setVisibility(View.GONE);

                } else {
                    videoView.setVideoPath(entity.getData().getData().get(i).getTv().getVideoSource360());
                    isPaused = false;
                    isPlaying = true;
                    System.out.println("播放新的视频");
                }
                videoView.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (videoView != null) {
                            videoView.seekTo(0);
                            videoView.stopPlayback();
                            currentIndex = -1;
                            isPaused = false;
                            isPlaying = false;
                            holder.progressBar.setVisibility(View.GONE);
                            tvAdapter.notifyDataSetChanged();
                        }
                    }
                });
                videoView.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        holder.progressBar.setVisibility(View.VISIBLE);
                        videoView.start();
                    }
                });

            } else {
                holder.videoPlayBtn.setVisibility(View.VISIBLE);
                holder.videoImage.setVisibility(View.VISIBLE);
                holder.videoNameText.setVisibility(View.VISIBLE);
                holder.progressBar.setVisibility(View.GONE);
            }
            holder.videoPlayBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    currentIndex = position;
                    playPosition = -1;
                    tvAdapter.notifyDataSetChanged();
                }
            });


            return view;
        }

    }

    static class ViewHolder {
        ImageView videoImage;
        TextView videoNameText;
        ImageButton videoPlayBtn;
        ProgressBar progressBar;
    }


}